from src.video import Video
from src.database import Database

import json

class History:

    def __init__(self) -> None:
        self.database   = Database()
        self.video_list = list()
        self._id_list   = list()
        self.load_history()

    def load_history(self) -> None:
        for item in self.database.load_history():
            try:
                item_text = item[0].replace("\"", "`")
                item_text = item_text.replace("\'", "\"")
                dct = json.loads(item_text)

                video = Video().from_history_dict(dct)
                if not video.videoId in self._id_list:
                    self.video_list.append(video)
                    self._id_list.append(video.videoId)
            except: continue
        self.video_list.reverse()

    def insert(self, video: Video) -> None:
        if not video.in_history(self): self.video_list.insert(0, video)
        self.database.insert_video_in_history(video.to_history_dict())

    def remove(self, video: Video) -> None:
        self.database.delete_video_from_history(video.to_history_dict())


